import { getCouponCenterList, setUserCoupon } from '../../services/user'
import { dateFormat } from '../../utils/date'
import { priceToYuan } from '../../utils/utils'

Page({
  data: {
    tickets: [],
    usedDict: {},
  },
  onLoad() {
    my.setNavigationBar({
      title: '领券中心',
      backgroundColor: '#4BA3F9'
    })
    this.getCouponCenterList()
  },
  getCouponCenterList() {
    getCouponCenterList({}).then(res => {
      if (res.code == 0) {
        this.setData({ tickets: res.data.list.map((item, index) => ({
          id: item.id,
          couponAmount: priceToYuan(item.discount),
          minPurchase: priceToYuan(item.threshold),
          couponStart: dateFormat(item.start_date),
          couponEnd: dateFormat(item.end_date),
          couponName: item.name,
          action: 0,
        }))})
      }
    })
  },
  onTap({ target: { dataset: { id } } }) {
    setUserCoupon({ id }).then(res => {
      if (res.code == 0) {
        // const usedDict = Object.assign(this.data.usedDict, { id: true })
        const { tickets } = this.data
        
        const index = tickets.findIndex(item => item.id === id)
        index > -1 && (tickets[index].action = 1)

        this.setData({ tickets })
        console.log('tickets', tickets)
      }
    })
  }
})
